package com.ee.chat.admin.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ee.chat.admin.service.IOperationService;
import com.ee.chat.admin.service.IVipService;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.dao.UserMapper;
import com.ee.chat.common.dao.UserVipLogMapper;
import com.ee.chat.common.dao.UserVipMapper;
import com.ee.chat.common.dao.VipConfigMapper;
import com.ee.chat.common.entity.*;
import com.ndhutu.ee.util.DateUtil;
import com.ndhutu.ee.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class VipServiceImpl implements IVipService {
    @Resource
    UserVipMapper userVipMapper;
    @Resource
    IOperationService operationService;
    @Resource
    VipConfigMapper vipConfigMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    UserVipLogMapper userVipLogMapper;

    @Override
    public Result list(HttpServletRequest request, Integer page, Integer limit, String keyword, String time) throws Exception {
        Map<String, Object> data = new HashMap<>();

        if(StringUtil.isEmpty(keyword) && StringUtil.isEmpty(time)){
            HttpSession session = request.getSession(true);
            List<String> userPermissions = (List<String>)session.getAttribute("userPermissions");
            if(!userPermissions.contains("/vip/viewList")){
                data.put("vipUsers", new ArrayList<>());
                data.put("total", 0);

                return Result.returnSuccess(data);
            }
        }

        Date beginTime = null, endTime = null;
        if(!StringUtil.isEmpty(time)){
            String[] arr = time.split(" - ");
            beginTime = DateUtil.parse(arr[0]);
            endTime = DateUtil.parse(arr[1]);
        }

        Page<Map<String, Object>> p = new Page<>(page, limit);
        IPage<Map<String, Object>> iPage = userVipMapper.list(p, keyword, beginTime, endTime);
        List<Map<String, Object>> vipUsers = iPage.getRecords();

        data.put("vipUsers", vipUsers);
        data.put("total", iPage.getTotal());

        operationService.addOperationLog(request, "获取vip用户数据列表");

        return Result.returnSuccess(data);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(HttpServletRequest request, Integer userId, Integer identity) throws Exception {
        User user = userMapper.selectById(userId);
        if(user == null){
            return Result.returnFailure("用户id不存在");
        }

        VipConfig vipConfig = vipConfigMapper.selectByIdentity(identity);

        LocalDateTime beginTime = LocalDateTime.now();
        LocalDateTime endTime = beginTime.plusMonths(vipConfig.getValidMonth());

        //添加/更新身份
        UserVip userVip = userVipMapper.getByUserId(userId);
        if(userVip == null){
            userVip = new UserVip(userId, identity, beginTime, endTime);
            userVipMapper.insert(userVip);
        }else{
            if(vipConfig.getIdentity() > userVip.getIdentity()){
                userVip.setIdentity(vipConfig.getIdentity());
                userVip.setBeginTime(beginTime);
                userVip.setEndTime(endTime);
            }else if(vipConfig.getIdentity().equals(userVip.getIdentity())){
                if(userVip.getEndTime().isAfter(LocalDateTime.now())){
                    endTime = userVip.getEndTime().plusMonths(vipConfig.getValidMonth());
                    userVip.setEndTime(endTime);
                }else{
                    userVip.setBeginTime(beginTime);
                    userVip.setEndTime(endTime);
                }
            }else{
                if(userVip.getEndTime().isAfter(LocalDateTime.now())){
                    endTime = userVip.getEndTime().plusMonths(vipConfig.getValidMonth());
                    userVip.setEndTime(endTime);
                }else{
                    userVip.setIdentity(vipConfig.getIdentity());
                    userVip.setBeginTime(beginTime);
                    userVip.setEndTime(endTime);
                }
            }
            userVipMapper.updateById(userVip);
        }

        //添加记录
        UserVipLog userVipLog = new UserVipLog(userId, 0, 4, 0, StringUtil.getOrderNumber(), 1);
        userVipLogMapper.insert(userVipLog);

        return Result.returnSuccess(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result del(HttpServletRequest request, List<Integer> ids) throws Exception {
        for(Integer id : ids){
            UserVip vip = userVipMapper.selectById(id);
            userVipMapper.deleteById(id);

            //获取最新购买会员记录
            UserVipLog vipLog = userVipLogMapper.queryLastVipLogByUserId(vip.getUserId());
            vipLog.setStatus(1);
            vipLog.setUpdateTime(new Date());
            userVipLogMapper.updateById(vipLog);
        }

        operationService.addOperationLog(request, "删除会员，ids："+ids);

        return Result.returnSuccess(null);
    }
}
